(function($) {
  "use strict";

  function Funtest() {
    this.data = {};
    this.answer = {};
    this.first_question = null;
    this.qid = null;
    this.hide_item = false;
    this.alias_qid = null;
    this.next_qid = null;
    this.testid = null;
    this.is_last = null;
    this.previous_qid = null;
    this.template = "normal_item";
    this.show_previous = function() {};
    this.hide_previous = function() {};
    this.show_done = function() {};
    this.hide_done = function() {};
    this.update_index = function() {};
    this.send_result = function() {};
    this.go_done = function() {};

    // view
    this.normal_item_box = [
      '<div class="question_box">',
      '  <h3 class="question_title">%{description}</h3>',
      '  <ul class="items_c">',
      '    %{items}',
      '  </ul>',
      '</div>'
    ].join("");

    this.normal_item = [
      '<li class="no_selectable question_item %{selected_item}" onclick="save_value(\'%{val}\', this)">%{txt}</li>'
    ].join("");

    this.flow_item_box = [
      '<div class="question_box">',
      '  <h3 class="question_title">%{description}</h3>',
      '  <ul class="items_c flow_item">',
      '    %{items}',
      '  </ul>',
      '<div  class="clear"></div>',
      '</div>'
    ].join("");

    this.flow_item = [
      '<li class="no_selectable question_item %{selected_item}" onclick="save_value(\'%{val}\', this)">%{txt}</li>'
    ].join("");


    this.image_item_box = [
      '<div class="question_box">',
      '  <h3 class="question_title">%{description}</h3>',
      '  <ul class="items_c">',
      '    %{items}',
      '  </ul>',
      '<div  class="clear"></div>',
      '</div>'
    ].join("");

    this.image_item = [
      '<li class="no_selectable question_item_image %{last_klass}" onclick="save_value(\'%{val}\', this)">',
      '  <img src="%{pic}?t=' + (new Date()).getTime() + '" />',
      '  <div class="question_item_text %{selected_item}">%{txt}</div>',
      '</li>'
    ].join("");



  }

  Funtest.prototype.setData = function(data) {
    var _data = {};
    $(data).each(function(index, item) {
      _data[item["qid"]] = item;
      // console.log(item)
    });
    this.data = _data;
    this.first_question = this.data["1"];
    return this;
  };

  Funtest.prototype.setTemplate = function(template) {
    this.template = template;
    return this;
  };

  Funtest.prototype.setHideItem = function(hide_or_not) {
    this.hide_item = hide_or_not;
    return this;
  };

  Funtest.prototype.setAnswer = function(answer) {
    this.answer = answer;
    return this;
  };

  Funtest.prototype.setTestid = function(testid) {
    this.testid = testid;
    return this;
  };

  Funtest.prototype.setControllFunctions = function(
    show_previous_func,
    hide_previous_func,
    show_done_func,
    hide_done_func,
    update_index_func,
    send_result_func,
    go_done_func
  ) {

    this.show_previous = show_previous_func;
    this.hide_previous = hide_previous_func;
    this.show_done = show_done_func;
    this.hide_done = hide_done_func;
    this.update_index = update_index_func;
    this.send_result = send_result_func;
    this.go_done = go_done_func;
  };

  Funtest.prototype.nextQid = function() {
    var curr_item = this.data[this.qid];
    var this_val = this.answer[this.qid];
    if (curr_item["guide_qids"] !== null && curr_item["guide_qids"][this_val] !== null) {
      // redirect by the answer of this question
      var _nextqid = curr_item["guide_qids"][this_val]["nextqid"];
      if (_nextqid == -1)
        this.send_result(this.testid, this.qid, curr_item["guide_qids"][this_val]["val"]);
      return _nextqid;
    } else {
      // redirect by the answers of this group questions
      return this.nextQid_group();
    }
  };

  Funtest.prototype.nextQid_group = function() {
    var a_count = 0,
      b_count = 0;

    var _this = this;
    $([1, 2, 3, 4, 5, 6, 7]).each(function() {
      var val = _this.answer[this];
      if (val) {
        if (val == "a") {
          a_count++;
        } else if (val == "b") {
          b_count++;
        }
      } //if val
    });
    var next_qid = 10;
    if (a_count > b_count) {
      next_qid = 19;
    }
    return next_qid;
  };

  Funtest.prototype.renderFirstItem = function() {
    this.renderItem(this.first_question);
  };

  Funtest.prototype.renderNextItem = function() {
    var curr_item = this.data[this.qid];
    if (curr_item["server_guide"] == "1") {
      // alert("need check answer and guide to next question.");
      this.next_qid = this.nextQid();
    }
    if (this.next_qid == "-1") {
      setTimeout(function() {
        this.go_done();
      }, 500);
      //            self.location = "/fun_tests/calc_result?testid="+ this.testid + "&userid=" + "19195";
    } else {
      var item = this.data[this.next_qid];
      this.renderItem(item);
    }
  };

  Funtest.prototype.renderPreviousItem = function() {
    var item = this.data[this.previous_qid];
    this.renderItem(item);
  };

  Funtest.prototype.sendResult = function() {
    // alert("sendResult");
  };

  Funtest.prototype.renderItem = function(item) {
    // console.log(item);
    this.qid = item["qid"];
    this.alias_qid = item["alias_qid"];
    this.next_qid = item["nextqid"];
    this.previous_qid = item["previousqid"];
    this.is_last = item["is_last"];

    // console.log("render item: " + item["qid"]);
    // console.log(item);
    var box_html = this[this.template + "_box"].replace("%{description}", item["description"]);
    var items = [];
    var _this = this;
    var i = 0;
    $(item["items"]).each(function() {
      i += 1;

      if (!_this.need_render_item(this)) {
        return;
      }

      var last_klass = "";
      if (i > 1) {
        last_klass = "question_item_image_last";
      }
      var selected_item = "";
      var val = this["val"];
      var answer = _this.answer[_this["qid"]];
      if (answer == val) {
        selected_item = " selected_item";
      }
      items.push(_this[_this.template].replace("%{val}", val)
        .replace("%{txt}", this["txt"])
        .replace("%{pic}", this["pic"])
        .replace("%{last_klass}", last_klass)
        .replace("%{selected_item}", selected_item));
    });
    box_html = box_html.replace("%{items}", items.join(""));
    // console.log(box_html)
    $(".question_c").html(box_html);

    this.renderController();
  };

  Funtest.prototype.need_render_item = function(item) {
    if (!this.hide_item) {
      return true;
    }
    for (var key in this.answer) {
      if (this.answer[key] == item["val"]) {
        return false;
      }
    }

    return true;
  };

  Funtest.prototype.renderController = function() {

    // hide item test kind not show previous
    if (parseInt(this.previous_qid, 10) > 0 && !this.hide_item) {
      this.show_previous();
    } else {
      this.hide_previous();
    }

    if (this.is_last) {
      this.show_done();
    } else {
      this.hide_done();
    }

    this.update_index(this.alias_qid || this.qid);

  };

  Funtest.prototype.saveValue = function(val) {
    this.send_result(this.testid, this.qid, val);
    this.answer[this.qid] = val;
    if (this.is_last) {
      // this.sendResult();
    } else {
      this.renderNextItem();
    }
  };

  window.Funtest = new Funtest();
})($);